package com.company.project.web;
import com.company.project.core.Result;
import com.company.project.core.ResultGenerator;
import com.company.project.model.Thesis;
import com.company.project.service.ThesisService;
import com.company.project.util.FileUploadUtil;
import com.company.project.util.PageUtil;
import com.company.project.util.ThesisAndAssessment;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* Created by CodeGenerator on 2018/10/08.
*/
@RestController
@RequestMapping("/thesis")
public class ThesisController {
    @Resource
    @Autowired
    private ThesisService thesisService;

    @Resource
    private Thesis thesis;

    @Resource
    private FileUploadUtil fileUploadUtil;

    //按论文查找
    @PostMapping(value = "/selectPer/{index}")
    public PageUtil queryThesis(@RequestBody String cname,@PathVariable("index")Integer index){
        PageUtil<Map<Object,Object>> thesisPageUtil = thesisService.queryThesis(cname, index);

        return thesisPageUtil;
    }

    //根据论文id查询论文详情
    @GetMapping("/selectParticularsById/{id}")
    @ResponseBody
    public Thesis selectParticularsById(@PathVariable(value = "id",required = false) Integer id){
        if (id==null || ("").equals(id)){
            return null;
        }
        Thesis theses = thesisService.selectParticularsById(id);
        return theses;
    }

    /**
     * 后台查询稿件管理
     * @param index
     * @return
     */
    @GetMapping("/selectManuscriptManagement/{index}")
    @ResponseBody
    public PageUtil<Thesis> selectManuscriptManagement(@PathVariable(value = "index",required = false) Integer index){
        PageUtil<Thesis> thesisPageUtil = thesisService.selectManuscriptManagement(index);
        return thesisPageUtil;
    }
    @PostMapping("/add")
    public Result add(Thesis thesis) {
        thesisService.save(thesis);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/delete")
    public Result delete(@RequestParam Integer id) {
        thesisService.deleteById(id);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/update")
    public Result update(Thesis thesis) {
        thesisService.update(thesis);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/detail")
    public Result detail(@RequestParam Integer id) {
        Thesis thesis = thesisService.findById(id);
        return ResultGenerator.genSuccessResult(thesis);
    }

    @PostMapping("/list")
    public Result list(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        List<Thesis> list = thesisService.findAll();
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    //稿件评估
    @PostMapping("/add/thesis")
    @ResponseBody
    public Result addThesis(@RequestBody ThesisAndAssessment thesisAndAssessment){
        Map<String,Integer> map =thesisService.addThesis(thesisAndAssessment);
        if(map.size()>0 ){
            return ResultGenerator.genSuccessResult(map);
        }
        return  ResultGenerator.getInternalServerErrot("系统内部错误");
    }

    //获取单个论文根据id
    @GetMapping("/select/thesis/{id}")
    @ResponseBody
    public Result getThesisById(@PathVariable Integer id) {
        Thesis thesis=thesisService.getThsisById(id);
        return ResultGenerator.genSuccessResult(thesis);
    }

    //后台查询全部稿件数量
    @GetMapping("/selectAllThesis/{index}")
    @ResponseBody
    public  PageUtil<Thesis> selectAllThesis(@PathVariable(value = "index") Integer index){
        PageUtil<Thesis> thesisPageUtil = thesisService.selectAllThesis(index);
        return thesisPageUtil;
    }

    /**
     *  查询全部稿件数量
     * @return
     */
    @GetMapping("/selectAllThesisUnm")
    @ResponseBody
    public Result selectAllThesisUnm(){
        Integer integer = thesisService.selectAllThesisUnm();
        return ResultGenerator.genSuccessResult(integer);
    }
    //待处理稿件
    @GetMapping("/selectPending/{index}")
    @ResponseBody
    public PageUtil<Thesis> selectPending (@PathVariable(value = "index",required = false) Integer index){
        PageUtil<Thesis> thesisPageUtil = thesisService.selectPending(index);
       return thesisPageUtil;
    }
    /**
     * 待处理稿件数量
     */
    @GetMapping("/selectPendingNum")
    @ResponseBody
    public Result selectPendingNum(){
        Integer integer = thesisService.selectPendingNum();
        return ResultGenerator.genSuccessResult(integer);
    }

    /**
     * 参考文献格式校验
     * @param data
     * @return
     */
    @PostMapping("/DocumentFormatCheck")
    @ResponseBody
    public Result DocumentFormatCheck (@RequestBody  String data){
        List list = thesisService.DocumentFormatCheck(data);
        return ResultGenerator.genSuccessResult(list);
    }

    /**
     * 错别字校验
     * @param map
     * @return
     */
    @PostMapping("/ProofreadForTypos")
    @ResponseBody
    public Result ProofreadForTypos(@RequestBody String map){
        List list = thesisService.ProofreadForTypos(map);
        return ResultGenerator.genSuccessResult(list);
    }

    /**
     * 创新指数检验
     * @param data
     * @return
     */
    @PostMapping("/ManuscriptInnovationIndex")
    @ResponseBody
    public JSONArray ManuscriptInnovationIndex(@RequestBody Map<String,String> data) throws UnsupportedEncodingException {
        List<Object> list = thesisService.ManuscriptInnovationIndex(data);
        JSONArray jsonArray = JSONArray.fromObject(list);
        return jsonArray;
    }

    /**
     * 论文功能整合
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/Integration")
    @ResponseBody
    public JSONObject Integration(MultipartFile file) throws IOException {
        InputStream isa = new ByteArrayInputStream(file.getBytes());
        Map<String, Object>map = new HashMap<>();
        Pattern p= Pattern.compile("^\\[[0-9]+\\]");
        List<String> list2 = new ArrayList<>();
        InputStream is = isa;
        POIFSFileSystem fs = new POIFSFileSystem(is);
        HWPFDocument document = new HWPFDocument(fs);
        Range range = document.getRange();
        String title = "";
        String zhaiyao = "";
        String keyword = "";
        String body = "";
        String txt = "";
        int start  = 0;
        int end = 0;
        for(int i = 0;i<(range.numParagraphs()-1);i++) {
            Paragraph paragraph = range.getParagraph(i);
            txt = paragraph.text().trim();
            Matcher m = p.matcher(txt);
            if(i==0){
                //标题
                title = txt;
                continue;
            }
            if(txt.replaceAll(" ", "").contains("摘要")) {
                zhaiyao = txt;
                continue;
            }
            if(txt.replaceAll(" ", "").contains("关键词")) {
                keyword = txt;
                continue;
            }
            if(txt.replaceAll(" ", "").toLowerCase().contains("keyword")) {
                start = i+1;
                continue;
            }
            if(txt.replaceAll(" ", "").toLowerCase().contains("参考文献")) {
                end = i-1;
                continue;
            }
            if(m.find()) {
                list2.add(txt);
                continue;
            }
        }
        StringBuilder builder = new StringBuilder();
        for(int i = start;i<=end;i++) {
            Paragraph paragraph = range.getParagraph(i);
            txt = paragraph.text().trim();
            builder.append(txt);
        }
        map.put("title",title);
        map.put("abstract", zhaiyao);
        map.put("keyword", keyword);
        map.put("body", builder.toString());
        map.put("references", list2);
        JSONObject object = JSONObject.fromObject(map);
        return object;
    }
}
